package com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.FlowVarExpressionVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowVarExpressionRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.entities.FlowVarExpression;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.entities.FlowVarExpressionExample;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.mapper.FlowVarExpressionDAO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author wuliepeng
 */
@Service
public class FlowVarExpressionRepositoryImpl implements FlowVarExpressionRepository {

    @Autowired
    private FlowVarExpressionDAO flowVarExpressionDAO;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertBatch(List<FlowVarExpressionVo> flowVarExpressions) {
        for (FlowVarExpressionVo flowVarExpression : flowVarExpressions) {
            if (Objects.nonNull(flowVarExpression)) {
                flowVarExpressionDAO.insert(convert(flowVarExpression));
            }
        }
    }

    /**
     * @param deployId
     * @param activityId
     * @return
     * @Description 根据部署ID和活动节点编码获取变量表达式记录集合
     * @author liujinjian
     * @date 2021-10-25
     */
    @Override
    public List<FlowVarExpressionVo> selectByDeployIdAndActivityId(String deployId, String activityId) {
        FlowVarExpressionExample query = new FlowVarExpressionExample();
        FlowVarExpressionExample.Criteria criteria = query.createCriteria().andDeployIdEqualTo(deployId);
        criteria.andActivityIdEqualTo(activityId);

        List<FlowVarExpression> configs = flowVarExpressionDAO.selectByExample(query);

        return configs.stream().map(this::convertToFlowVarExpressionVo).collect(Collectors.toList());
    }

    private FlowVarExpressionVo convertToFlowVarExpressionVo(FlowVarExpression entity) {
        if (Objects.isNull(entity)) {
            return  null;
        }

        FlowVarExpressionVo result = new FlowVarExpressionVo();
        BeanUtils.copyProperties(entity,result);
        return result;
    }

    private FlowVarExpression convert(FlowVarExpressionVo entity) {
        if (Objects.isNull(entity)) {
            return null;
        }
        FlowVarExpression result = new FlowVarExpression();
        BeanUtils.copyProperties(entity, result);
        return result;
    }
}
